package com.uml.umlwork.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uml.umlwork.dto.news.NewsDTO;
import com.uml.umlwork.entity.News;
import com.uml.umlwork.mapper.NewsMapper;
import com.uml.umlwork.service.NewsService;
import com.uml.umlwork.vo.news.NewsVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Youens
 * @date 2021-01-03 14:07
 */
@Service
public class NewsServiceImpl implements NewsService {
    private final NewsMapper newsMapper;

    public NewsServiceImpl(NewsMapper newsMapper) {
        this.newsMapper = newsMapper;
    }


    @Override
    public Page<NewsVO> getAllNews(Long current, Long size, Integer publish) {

        List<NewsVO> collect = newsMapper.selectList(null).stream().map(NewsVO::new)
                .collect(Collectors.toList());
        if (publish != null) {
            collect = collect.stream().filter(newsVO -> newsVO.getRelease() == publish.equals(1))
                    .collect(Collectors.toList());
        }
        Page<NewsVO> page = new Page<NewsVO>(current, size)
                .setTotal(collect.size())
                .setRecords(collect);
        return page;
    }

    @Override
    public void releaseNewsByNewsId(Integer newsId, Boolean release) {
        News news = getNewsById(newsId);
        news.setPublish(release);
        newsMapper.updateById(news);
    }

    @Override
    public void saveNews(NewsDTO dto) {
        News news = new News();
        if (dto.getNewId() != null) {
            news = getNewsById(dto.getNewId());
            news.setTitle(dto.getTitle())
                    .setContent(dto.getContent());
            newsMapper.updateById(news);
        } else {
            news.setContent(dto.getContent())
                    .setPublish(false)
                    .setTitle(dto.getTitle());
            newsMapper.insert(news);
        }
    }

    private News getNewsById(Integer newsId) {
        return Optional.ofNullable(newsMapper.selectById(newsId))
                .orElseThrow(() -> new RuntimeException("该id:" + newsId + "有误"));
    }
}
